from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

# 生成token
from users.models import User


def generate_verify_email_url(user):
    # 1, 取到用户信息
    data = {
        'userid': user.id,
        'email': user.email
    }
    # 2, 加密用户信息
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 30)
    token = s.dumps(data).decode()  # qwe12312erwscewsf3423
    # 3, 生成链接
    url = '%s?token=%s' % (settings.EMAIL_VERIFY_URL, token)
    # 4, 返回链接
    return url


# 解密token
def decode_token(token):
    # 1, 生成 Serializer 对象
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=60 * 30)

    # 2, 解密token
    try:
        data = s.loads(token)
    except Exception as e:
        return None
    # 3, 得到userid
    userid = data.get('userid')

    # 4, 根据id 获得用户
    user = User.objects.get(id=userid)

    # 5, 返回用户
    return user
